package com.aijia.custom.product.ui;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.aijia.custom.product.R;
import com.aijia.custom.product.customview.LoadingWaitDialog;
import com.aijia.custom.product.data.LoginResponse;
import com.aijia.custom.product.listener.ILoginListener;
import com.aijia.custom.product.manager.LoginManager;
import com.aijia.custom.product.utils.Notification;
import com.aijia.custom.product.utils.SharedPreferencesUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import rx.Observer;


/**
 * Created by yejianjun on 2019/1/14.
 */

public class SplashActivity extends Activity implements ILoginListener {
    private final String TAG = SplashActivity.class.getSimpleName();
    private Handler handler;
    private boolean autoStatus;
    private LoginManager manager;
    private Dialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        // 定时器
        handler = new Handler();
        initPermission();

    }

    private void init() {

        if (getAutoStatus()) {
            manager = new LoginManager(this);
            manager.addLoginListener(this);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    autoLogin();
                }
            });
        } else {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    intoLoginActivity();
                }
            }, 1 * 1000);
        }

    }


    private boolean getAutoStatus() {
        autoStatus = SharedPreferencesUtils.getAutoLoginStatus(this);
        String username = SharedPreferencesUtils.getUserName(this);
        String password = SharedPreferencesUtils.getPassword(this);
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            SharedPreferencesUtils.setAutoLoginStatus(this, false);
            autoStatus = false;
        }
        return autoStatus;
    }

    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onCompleted() {
                        // 权限回调完成
                        Log.d(TAG, "onCompleted...");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError...");
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.d(TAG, "onNext... " + aBoolean);
                        if (!aBoolean) {
                            Notification.toast(SplashActivity.this, "您需要开启权限,并重启应用");
                            finish();
                        } else {
                            init();
                        }
                    }
                });

    }


    private void autoLogin() {
        //------------这个为兼容性测试所用-------------------
//        auto_status = true;
//        username = "13900000006";
//        password = Utils.Md5("123456");
        //------------------------------------------------
        String username = SharedPreferencesUtils.getUserName(this);
        String password = SharedPreferencesUtils.getPassword(this);
        manager.login(username, password);
        // 登录等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "登录中...");
        dialog.show();
    }

    private void intoLoginActivity() {
        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
        SplashActivity.this.finish();
    }


    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        // 自动登录失败，跳转到登录界面
        intoLoginActivity();
    }

    @Override
    public void onLoginSuccess(LoginResponse response) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }

        /**
         * 保存用户类型： 1. 店长，2，老板，3. 员工
         */
        SharedPreferencesUtils.setUserType(this, response.getStaff().getUseType());
        // 自动登录状态改成true
        SharedPreferencesUtils.setAutoLoginStatus(this, true);
        // 当前登录的用户ID
        SharedPreferencesUtils.setUserID(this, response.getStaff().getId());

        SharedPreferencesUtils.setOrganizeName(this, response.getStaff().getOrganizeName());
        SharedPreferencesUtils.setOrganizeId(this, response.getStaff().getOrganizeId());
        SharedPreferencesUtils.setToken(this, response.getToken());


        // 自动登录成功， 跳转到主界面
        Intent intent = new Intent();
        intent.putExtra("user_type", response.getStaff().getUseType());
        intent.setClass(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
